import sys
import os
import time
from pathlib import Path

from env import setting

# 确保日志目录存在
log_dir = Path('./logs')
log_dir.mkdir(exist_ok=True)

# 使用日期作为日志文件标识
PROCESS_ID = "{time:YYYY-MM-DD}"

# 日志级别映射
LOG_LEVEL_MAP = {
    "DEBUG": "DEBUG",
    "INFO": "INFO",
    "WARNING": "WARNING",
    "ERROR": "ERROR",
    "CRITICAL": "CRITICAL"
}

# 获取配置的日志级别
log_level = LOG_LEVEL_MAP.get(setting.SYS_LOG_LEVEL.upper() if hasattr(setting, 'SYS_LOG_LEVEL') else "DEBUG", "DEBUG")
app_log_level = LOG_LEVEL_MAP.get(setting.LOG_LEVEL.upper() if hasattr(setting, 'LOG_LEVEL') else "INFO", "INFO")

# 定义通用格式
CONSOLE_FORMAT = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | " \
                "<level>{level: <8}</level> | " \
                "{thread.name: <12} | " \
                "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | " \
                "<level>{message}</level>"

FILE_FORMAT = "{time:YYYY-MM-DD HH:mm:ss.SSS} | " \
             "{level: <8} | " \
             "{thread.name: <12} | " \
             "{name}:{function}:{line} | " \
             "{message}"

ERROR_FORMAT = "{time:YYYY-MM-DD HH:mm:ss.SSS} | " \
              "{level: <8} | " \
              "{thread.name: <12} | " \
              "{name}:{function}:{line} | " \
              "{message}\n{exception}"

# 获取安全的轮转设置
def get_safe_rotation():
    # 尝试从setting中获取，默认为每天午夜
    if hasattr(setting, 'ROTATION') and setting.ROTATION:
        try:
            rotation = setting.ROTATION
            # 如果是元组格式，取第一个元素
            if isinstance(rotation, tuple) and len(rotation) > 0:
                return rotation[0]
            return rotation
        except:
            return "00:00"
    return "00:00"

# 获取安全的保留设置
def get_safe_retention():
    # 尝试从setting中获取，默认为7天
    if hasattr(setting, 'RETENTION') and setting.RETENTION:
        return setting.RETENTION
    return "7 days"

# 获取安全的压缩设置
def get_safe_compression():
    # 尝试从setting中获取，默认为zip
    if hasattr(setting, 'COMPRESSION') and setting.COMPRESSION:
        try:
            compression = setting.COMPRESSION
            # 如果是元组格式，取第一个元素
            if isinstance(compression, tuple) and len(compression) > 0:
                return compression[0]
            return compression
        except:
            return "zip"
    return "zip"

# 安全地获取日志文件写入设置
write_to_console = getattr(setting, 'LOG_IS_WRITE_TO_CONSOLE', True)
write_to_file = getattr(setting, 'LOG_IS_WRITE_TO_FILE', True)

# 日志配置
loguru_config = {
    "handlers": [
        # 控制台日志
        {
            "sink": sys.stdout,
            "level": log_level,
            "format": CONSOLE_FORMAT,
            "colorize": True,
            "backtrace": True,
            "diagnose": True,
            "enqueue": True,  # 启用线程安全
        } if write_to_console else None,
        
        # 应用日志文件
        {
            "sink": os.path.join(log_dir, 'core_app_{time:YYYY-MM-DD}.log'),
            "level": app_log_level,
            "format": FILE_FORMAT,
            "rotation": get_safe_rotation(),  # 日志轮转策略
            "retention": get_safe_retention(),  # 日志保留策略
            "compression": get_safe_compression(),  # 压缩
            "encoding": 'utf-8',
            "enqueue": True,  # 启用线程安全
            "backtrace": True,
            "diagnose": True,
        } if write_to_file else None,
        
        # 错误日志文件
        {
            "sink": os.path.join(log_dir, 'core_error_{time:YYYY-MM-DD}.log'),
            "level": "ERROR",
            "format": ERROR_FORMAT,
            "rotation": get_safe_rotation(),  # 日志轮转策略
            "retention": get_safe_retention(),  # 日志保留策略
            "compression": get_safe_compression(),  # 压缩
            "encoding": 'utf-8',
            "backtrace": True,
            "diagnose": True,
            "enqueue": True,  # 启用线程安全
        } if write_to_file else None,
        
        # 访问日志文件
        {
            "sink": os.path.join(log_dir, 'core_access_{time:YYYY-MM-DD}.log'),
            "level": "INFO",
            "format": FILE_FORMAT,
            "filter": lambda record: "访问" in record["message"],
            "rotation": get_safe_rotation(),  # 日志轮转策略
            "retention": get_safe_retention(),  # 日志保留策略
            "compression": get_safe_compression(),  # 压缩
            "encoding": 'utf-8',
            "enqueue": True,  # 启用线程安全
        } if write_to_file else None,
    ],
    # 添加额外信息
    "extra": {"app_name": "yhpc_back"},
    # 移除自定义日志级别定义，因为 loguru 已经内置了这些级别
}

# 移除None值的处理器
loguru_config["handlers"] = [h for h in loguru_config["handlers"] if h is not None]
